using System.Collections;
using Concurso;
using Curriculum.Metadatos.ClasesMetadatos;
using Curriculum.Modelo.Clases;
using Curriculum.Services;

namespace ConcursoCV.UI.WebUserControls.Concurso
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;

	/// <summary>
	///		Summary description for ABMAntecedenteConcurso.
	/// </summary>
	public class ABMAntecedenteConcurso : System.Web.UI.UserControl
	{
		protected System.Web.UI.WebControls.Button Button1;
		protected System.Web.UI.WebControls.Button btnAceptar;
		protected System.Web.UI.WebControls.RadioButtonList rblTipo;
		protected System.Web.UI.WebControls.Label lblCount;
		protected System.Web.UI.WebControls.Button btnAgregar;
		protected System.Web.UI.WebControls.Button btnCancelarAgregar;
		protected System.Web.UI.WebControls.Panel pnlAtributo;
		protected System.Web.UI.WebControls.TextBox txtMetrica;
		protected System.Web.UI.WebControls.TextBox txtTope;
		protected System.Web.UI.WebControls.TextBox txtNombre;
		protected System.Web.UI.WebControls.DataGrid dtgAdhocs;
		protected System.Web.UI.WebControls.TextBox txtNombreAdhoc;
		protected System.Web.UI.WebControls.RequiredFieldValidator rfvNombreAdhoc;
		protected System.Web.UI.WebControls.ValidationSummary valSum;
		protected System.Web.UI.WebControls.Button btnAgregarAdhoc;
		protected System.Web.UI.WebControls.Label lblConfirmacionOperacion;
		protected System.Web.UI.WebControls.Button btnCancelar;

		public event EventHandler Actualizar;
		public event EventHandler Cancelar;
		
		private void Page_Load(object sender, System.EventArgs e)
		{
			lblConfirmacionOperacion.Text = string.Empty;
			SetAttributesToControls();
			if(!this.IsPostBack)
			{
				this.ConcursoId = this.Request["concursoId"];
			}
		}


		#region - SetAttributesToControls -

		private void SetAttributesToControls()
		{
			this.txtTope.Attributes.Add("onKeyPress","return isNumberKey(event)");
		}

		#endregion - SetAttributesToControls -

		#region - LoadMethods -

		public void CargarAntecedenteAControl(string idAntecedenteMetadato)
		{
			VersionMetadatosService svc = new VersionMetadatosService();
			AntecedenteMetadato aMetadato = svc.ObtenerAntecedenetMetadato(idAntecedenteMetadato);
			AntecedenteMetadatoId = aMetadato.Id;
			txtNombre.Text = aMetadato.Nombre;
			CargarClasificacionMetricayTope();
			LlenarDataGridAdhocs();
		}

		private void CargarClasificacionMetricayTope()
		{
			ConcursoService svc = new ConcursoService();
			rblTipo.SelectedValue = svc.EsAntecedenteEspecifico(AntecedenteMetadatoId , ConcursoId) == false ? "2" : "1";
			DatosValoracion objDatosValoracion = svc.ObtenerMetricaYTope( ConcursoId, AntecedenteMetadatoId );
			if( objDatosValoracion != null )
			{
				txtMetrica.Text = objDatosValoracion.Metrica;
				txtTope.Text = objDatosValoracion.Tope != 0 ? objDatosValoracion.Tope.ToString() : string.Empty;
			}
			else
			{
				txtMetrica.Text = string.Empty;
				txtTope.Text = string.Empty;
			}
		}

		#endregion - LoadMethods -

		public void Nuevo ()
		{
			AntecedenteMetadatoId = "0";
			LimpiarControles();
			EnabledDisableControls(true);
			lblCount.Text = "0";
		}

		public void Modificacion ()
		{
			EnabledDisableControls(true);
		}

		public void EnabledDisableControls(bool enabled)
		{
			txtNombre.Enabled = enabled;
			btnAgregarAdhoc.Visible = enabled;
			btnAceptar.Visible = enabled;
			btnCancelar.Visible = enabled;
			dtgAdhocs.Columns[2].Visible = enabled;
		}

		private void LimpiarControles()
		{
			txtNombre.Text = string.Empty;
			dtgAdhocs.DataSource = new ArrayList();
			dtgAdhocs.DataBind();
		}

		private void VisiblePnlAtributo(bool visible)
		{
			pnlAtributo.Visible = visible;
		}
		private void EnabledButtons(bool enabled)
		{
			btnAceptar.Enabled = enabled;
			btnCancelar.Enabled = enabled;
		}

		#region - Crear, Modificar -

		private void CrearAntecedenteMetadato(AntecedenteMetadato aMetadato)
		{
			VersionMetadatosService svc = new VersionMetadatosService();
			AntecedenteMetadatoId = (string) svc.CrearAntecedenteMetadato(aMetadato);
		}
		private void ModificarAntecedenteMetadato(AntecedenteMetadato aMetadato)
		{
			VersionMetadatosService svc = new VersionMetadatosService();
			svc.ModificarAntecedenteMetadato(aMetadato);			
		}

		#endregion - Crear, Modificar -

		private void Guardar()
		{
			try
			{
				ConcursoService svc = new ConcursoService();
				svc.DesignarSiEsAntecedenteEspecifico( AntecedenteMetadatoId , ConcursoId, rblTipo.SelectedValue == "2" ? false : true);
				svc.AsignarMetricaYTope( txtTope.Text.Trim() != string.Empty ? int.Parse(txtTope.Text.Trim()) : 0,
					txtMetrica.Text.Trim() != string.Empty ? txtMetrica.Text.Trim() : null,
					ConcursoId,
					AntecedenteMetadatoId
					);
				lblConfirmacionOperacion.Text = "Los datos han sido grabados correctamente";
			}
			catch(Exception ex)
			{
				lblConfirmacionOperacion.Text = "Se ha producido un ERROR";
			}
		}		

		#region - Adhoc -

		private void CleanControlsAdhocs()
		{
			txtNombreAdhoc.Text = string.Empty;
		}

		private void LlenarDataGridAdhocs()
		{
			IList list = ObtenerListaAdhocs();
			lblCount.Text = list.Count.ToString();
			dtgAdhocs.DataSource = list;
			try 
			{
				dtgAdhocs.DataBind();				
			}
			catch( Exception ex )
			{
				string msg = ex.Message ;
				dtgAdhocs.CurrentPageIndex=0;
				LlenarDataGridAdhocs();
			}
			list = null;
		}
		private IList ObtenerListaAdhocs()
		{
			ConcursoService svc = new ConcursoService();
			return svc.ObtenerAdHocs( ConcursoId , AntecedenteMetadatoId );
		}

		private void EliminarAdhoc(string adhocId)
		{
			ConcursoService svc = new ConcursoService();
			svc.EliminarAdHoc( adhocId );
		}

		private void GuardarAdhoc()
		{
			if( PageModeAdhoc == PageMode.NEW )
			{
				CrearAdhoc();
			}
			else
			{
				if( PageModeAdhoc == PageMode.EDIT )
				{
					ModificarAdhoc();
				}
			}
		}

		private void CrearAdhoc()
		{
			ConcursoService svc = new ConcursoService();
			svc.CrearAdHod(ConcursoId, AntecedenteMetadatoId, txtNombreAdhoc.Text);
		}

		private void ModificarAdhoc()
		{
			ConcursoService svc = new ConcursoService();
			svc.ModificarAdHoc(AdhocId, txtNombreAdhoc.Text);
		}

		private void CargarAdhocAControl(string adhocId)
		{
			ConcursoService svc = new ConcursoService();
			txtNombreAdhoc.Text = svc.ObtenerAdHoc( adhocId ).Descripcion;
		}

		#endregion - Adhoc -

		#region - properties -
		
		public PageMode PageMode
		{
			get{ return (PageMode) ViewState["_mode"];}
			set{ ViewState["_mode"] = value;}
		}

		public PageMode PageModeAdhoc
		{
			get{ return (PageMode) ViewState["_modeAdhoc"];}
			set{ ViewState["_modeAdhoc"] = value;}
		}
		
		public string AntecedenteMetadatoId
		{
			get{ return (string) ViewState["_antecedenteMetadatoId"];}
			set{ ViewState["_antecedenteMetadatoId"] = value;}
		}

		public string ConcursoId
		{
			get{ return (string) ViewState["_concursoId"];}
			set{ ViewState["_concursoId"] = value;}
		}
		public string AdhocId
		{
			get{ return (string) ViewState["_adhocId"];}
			set{ ViewState["_adhocId"] = value;}
		}

		#endregion - properties -

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnAceptar.Click += new System.EventHandler(this.btnAceptar_Click);
			this.btnCancelar.Click += new System.EventHandler(this.btnCancelar_Click);
			this.dtgAdhocs.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dtgAdhocs_ItemCommand);
			this.dtgAdhocs.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dtgAdhocs_PageIndexChanged);
			this.btnAgregarAdhoc.Click += new System.EventHandler(this.btnAgregarAdhoc_Click);
			this.btnAgregar.Click += new System.EventHandler(this.btnAgregar_Click);
			this.btnCancelarAgregar.Click += new System.EventHandler(this.btnCancelarAgregar_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void btnAgregar_Click(object sender, System.EventArgs e)
		{			
			GuardarAdhoc();
			LlenarDataGridAdhocs();
			VisiblePnlAtributo(false);
			btnAgregarAdhoc.Enabled = true;
		}

		private void btnCancelarAgregar_Click(object sender, System.EventArgs e)
		{
			VisiblePnlAtributo(false);
		}

		private void dtgAdhocs_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			if ( e.CommandName != "Page" ) 
			{
				string adhocId = e.Item.Cells[0].Text;				
				switch ( e.CommandName ) 
				{
					case "Modificar":
							PageModeAdhoc = PageMode.EDIT;
							AdhocId = adhocId;
							CargarAdhocAControl(adhocId);
							VisiblePnlAtributo(true);
						break;
					case "Eliminar":
							PageModeAdhoc = PageMode.DELETE;
							EliminarAdhoc(adhocId);
							LlenarDataGridAdhocs();
						break;
					default:
						throw new Exception("comando incorrecto");
				}
			}					
		}

		private void btnAceptar_Click(object sender, System.EventArgs e)
		{
			Guardar();
		}

		private void dtgAdhocs_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
		{
			dtgAdhocs.CurrentPageIndex = e.NewPageIndex;
			LlenarDataGridAdhocs();
		}

		private void btnCancelar_Click(object sender, System.EventArgs e)
		{
			this.RaiseCancelar();
		}

		private void btnAgregarAdhoc_Click(object sender, System.EventArgs e)
		{
			PageModeAdhoc = PageMode.NEW;
			VisiblePnlAtributo(true);
			CleanControlsAdhocs();
			btnAgregarAdhoc.Enabled = false;
			btnAgregar.Enabled = true;
		}
		
		#region - RaiseEvents -

		protected void RaiseActualizar() 
		{
			if (this.Actualizar != null)
				this.Actualizar(this, null);		
		}
		protected void RaiseCancelar () 
		{
			if (this.Cancelar != null)
				this.Cancelar(this, null);		
		}

		#endregion - RaiseEvents -

	}
}
